package xing2387.filtervideoplayer.item

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import xing2387.filtervideoplayer.R
import xing2387.filtervideoplayer.databinding.FragmentFilterVideoPageBinding
import xing2387.filtervideoplayer.filter.GlBlurBackgroundFilter
import xing2387.filtervideoplayer.filter.GlBoxBlurFilter
import xing2387.filtervideoplayer.filter.GlFastGaussianBlurFilter
import xing2387.filtervideoplayer.filter.TestFilter
import xing2387.filtervideoplayer.player.GLPlayer

class FilterVideoPageFragment(videoUrl: String) : VideoPageFragment(videoUrl) {

    companion object {
        private const val TAG = "FilterVideoPageFragment"
        public fun newInstance(videoUrl: String): FilterVideoPageFragment {
            return FilterVideoPageFragment(videoUrl)
        }
    }

    constructor() : this("")

    private val binding: FragmentFilterVideoPageBinding by lazy {
        DataBindingUtil.inflate(
            LayoutInflater.from(context),
            R.layout.fragment_filter_video_page,
            null, false
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.ivBtnPlay.setOnClickListener {
            if (GLPlayer.sInstance.isPlaying()) {
                GLPlayer.sInstance.pauseVideo()
            } else {
                GLPlayer.sInstance.resumeVideo()
            }
        }
        binding.playerView.post {
//            binding.playerView.setGlFilter(TestFilter())
            binding.playerView.setGlFilter(GlFastGaussianBlurFilter())
//            binding.playerView.setGlFilter(GlBoxBlurFilter())
//            binding.playerView.setGlFilter(GlBlurBackgroundFilter(binding.playerView.width, binding.playerView.height, 0))
        }
    }

    override fun onAttachPlayer() {
        Log.d(TAG, "onAttachPlayer: $videoUrl")
        binding.playerView.setSimpleExoPlayer(GLPlayer.sInstance.exoPlayer)
        GLPlayer.sInstance.startVideo(videoUrl)
        binding.playerView.onResume()
    }

    override fun onDetachPlayer() {
        Log.d(TAG, "onDetachPlayer: $videoUrl")
        GLPlayer.sInstance.pauseVideo()
    }

    override fun onPause() {
        super.onPause()
        binding.playerView.onPause()
    }

    override fun onResume() {
        super.onResume()
        binding.playerView.onResume()
    }

}